import { useEffect, useRef } from 'react'
import THREEProject from '../utils/index'
import * as $ from 'd3'

const MapGeometry = () => {
  const can = useRef(null)
  const pro = new THREEProject([0.01,0.01,0.3])
  const { thr, renderer, scene, axes, camera, controls } = pro
  const fl = new thr.FileLoader()
  const init = () => {
    scene.add(axes)
    const group = new thr.Group()
    fl.load('/assets/hanjiangmian.json', res => {
      const { features } = JSON.parse(res)
      console.log("🚀 ~ file: MapGeometry.js ~ line 15 ~ init ~ features", features)
      for(let element of features) {
        let meshs = drawShap(element)
        meshs.forEach(mesh => {
          group.add(mesh)
        })
        
      }
      console.log('group', group)
      scene.add(group)
    })
    
    appendRenderDom()
    animate()
  }

  const drawShap = (element) => {
    const { geometry } = element
    const { coordinates } = geometry
    const shapeArr = []
    for(let face of coordinates ) {
      let points = []
      for(let point of face) {
        points.push(new thr.Vector2(point[0] - 116.7 , point[1] - 23.5))
      }
      let shape = new thr.Shape(points)
      shapeArr.push(shape)
    }
    const meshArr = []
    for(let shape of shapeArr) {
      const shapeGeometry = new thr.ExtrudeGeometry(
        shape,
        {
          depth: 0.01,
          bevelEnabled: false
        }
      )
      const material = new thr.MeshBasicMaterial( {
        color: 0xffffff * Math.random(),
        side: thr.DoubleSide
      } )
      const mesh = new thr.Mesh(shapeGeometry, material)
      meshArr.push(mesh)
    }
    
    // mesh.scale.set(1000,1000,1000)
    // mesh.position.set(-100, -100 ,0)
    return meshArr
  }


  const appendRenderDom = () => {
    if(!can.current.children.length) {
      can.current.appendChild(renderer.domElement)
    }
  }

  const render = () => {
    controls.update()
    renderer.render(scene, camera)
  }

  const animate = () => {
    requestAnimationFrame(animate)
    render()
  }

  useEffect(init, [])

  return (
    <div ref={can}></div>
  )
}

export default MapGeometry
export {
  MapGeometry
}